package com.siteseat.crudeq.common.raw;

import com.siteseat.common.misc.IOHelper;
import com.siteseat.crudeq.common.raw.Constants.MESSAGE;

/**
 * 
 */
public class MessageHelper implements Constants.MESSAGE {

  /**
   * @param raw
   * @param start
   * @return
   */
  public static byte readMagic( byte[] raw, int start ) {
    return raw[start + OFFSET.MAGIC];
  }

  /**
   * @param raw
   * @param start
   * @return
   */
  public static void writeMagic( byte[] raw, int start ) {
    raw[start + OFFSET.MAGIC] = MESSAGE.magic;
  }
  

  public static boolean isValidMagic( byte[] raw, int start ) {
    return readMagic( raw, start ) == MESSAGE.magic;
  }
  
  /**
   * @param raw
   * @param start
   * @return
   */
  public static int readSize( byte[] raw, int start ) {
    return IOHelper.readInt( raw, start + OFFSET.SIZE );
  }

  /**
   * @param raw
   * @param start
   * @return
   */
  public static void writeSize( byte[] raw, int start, int size ) {
    IOHelper.writeInt( raw, start + OFFSET.SIZE, size );
  }

  /**
   * @param raw
   * @param start
   * @return
   */
  public static long readTimestamp( byte[] raw, int start ) {
    return IOHelper.readLong( raw, start + OFFSET.TIMESTAMP );
  }

  /**
   * @param raw
   * @param start
   * @return
   */
  public static boolean isCommitted( byte[] raw, int start ) {
    return isCommited( readTimestamp( raw, start ) );
  }

  
  /**
   * @param timestamp
   * @return
   */
  public static boolean isCommited( long timestamp ) {
    return timestamp > 0;
  }

  /**
   * @param raw
   * @param start
   * @param committed
   */
  public static void setCommitted( byte[] raw, int start, boolean committed ) {
    writeTimestamp( raw, start, committed ? System.currentTimeMillis() : 0 );
  }

  /**
   * @param raw
   * @param start
   * @return
   */
  public static void writeTimestamp( byte[] raw, int start, long timestamp ) {
    IOHelper.writeLong( raw, start + OFFSET.TIMESTAMP, timestamp );
  }

  /**
   * @param raw
   * @param offset
   * @param size
   * @param validCode
   */
  public static void prepare( byte[] raw, int offset, int size ) {
    writeMagic( raw, offset );
    writeSize( raw, offset, size );
    setCommitted( raw, offset, false );
  }

}
